package com.cj.mvvmlib.base

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.cj.mvvmlib.fontsliderbar.PreferencesHelper


open class BaseApp(override val viewModelStore: ViewModelStore) : Application(),
    ViewModelStoreOwner {
    private lateinit var mAppViewModelStore: ViewModelStore

    private var mFactory: ViewModelProvider.Factory? = null

    override fun onCreate() {
        super.onCreate()
        mAppViewModelStore = ViewModelStore()
    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, this.getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }

    companion object {
        lateinit var appContext: Application

        @SuppressLint("StaticFieldLeak")
        var ph: PreferencesHelper? = null

        @Synchronized
        fun getContext(): Application {
            return appContext
        }

        fun initContext(context: Application) {
            appContext = context
            ph = PreferencesHelper(context, "test")
        }

        fun getPreferencesHelper(): PreferencesHelper? {
            return ph
        }

        /**
         *
         * @return 获取字体缩放比例
         */
        fun getFontScale(): Float {
            val currentIndex = ph?.getValueInt("currentIndex", 1) ?: 0
            return 1 + currentIndex * 0.1f
        }
    }
}